package com.agile.leetcode.baiduai.annimalidentity;


import com.agile.leetcode.baiduai.token.TokenConstant;
import com.agile.leetcode.baiduai.token.TokenUtil;
import com.agile.leetcode.baiduai.utils.FileUtil;
import com.agile.leetcode.baiduai.utils.HttpUtil;
import com.baidu.aip.util.Base64Util;

import java.net.URLEncoder;

/**
 * 百度ai只能识别图片
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/14 10:40
 */
public class Animal {
    public static void main(String[] args) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
        try {
            // 本地文件路径
            String filePath = "C:\\Users\\Administrator\\Pictures\\gou.jpg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = TokenUtil.getToken(TokenConstant.App_key.getValue(), TokenConstant.Secret_key.getValue());

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
